package com.zyy.servlet;

import com.alibaba.fastjson.JSON;
import com.mysql.jdbc.StringUtils;
import com.zyy.pojo.Role;
import com.zyy.pojo.User;
import com.zyy.service.role.RoleService;
import com.zyy.service.role.impl.RoleServiceImpl;
import com.zyy.service.user.UserService;
import com.zyy.service.user.impl.UserServiceImpl;
import com.zyy.util.Constants;
import com.zyy.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: UserServlet
 * @Description: Servlet复用
 * @Author: zyy
 * @Date: 2022/01/15 15:39
 * @Version: 1.0
 */
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method != null) {
            if ("savepwd".equals(method)) {
                updatePwd(req, resp);
            } else if ("checkoldpwd".equals(method)) {
                checkOldPwd(req, resp);
            } else if ("query".equals(method)) {
                query(req, resp);
            } else if ("add".equals(method)) {
                add(req, resp);
            } else if ("getrolelist".equals(method)) {
                getRoleList(req, resp);
            } else if ("ucexist".equals(method)) {
                userCodeExist(req, resp);
            }
        }
    }

    protected void userCodeExist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userCode = req.getParameter("userCode");

        UserService userService = new UserServiceImpl();
        User user = userService.getLoginUser(userCode);
        String msg = "not exist";
        if (user != null) {
            msg = "exist";
        }
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("userCode", msg);
        //返回
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

    protected void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //取数
        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        //返回
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(roleList));
        writer.flush();
        writer.close();
    }


    protected void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从session获取用户id
        Object obj = req.getSession().getAttribute(Constants.USER_SESSION);
        //获取入参中的新密码
        String newPassWord = req.getParameter("newpassword");
        if (obj == null || StringUtils.isNullOrEmpty(newPassWord)) {
            req.setAttribute("message", "新密码不可为空~");
        } else {
            UserService userService = new UserServiceImpl();
            boolean flag = userService.updatePwd(((User) obj).getId(), newPassWord);
            if (flag) {
                req.setAttribute("message", "密码修改成功，请退出，使用新密码登录~");
                //修改成功，移除session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            } else {
                req.setAttribute("message", "密码修改失败~");
            }
        }
        req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
    }

    protected void checkOldPwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从session中获取旧密码
        Object obj = req.getSession().getAttribute(Constants.USER_SESSION);
        //获取入参中的旧密码
        String oldPassWord = req.getParameter("oldpassword");
        Map<String, Object> resultMap = new HashMap<String, Object>(16);
        if (obj == null) {
            //session过期
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldPassWord)) {
            //旧密码输入为空
            resultMap.put("result", "error");
        } else {
            if (oldPassWord.equals(((User) obj).getUserPassword())) {
                //旧密码输入正确
                resultMap.put("result", "true");
            } else {
                //旧密码输入有误
                resultMap.put("result", "false");
            }
        }

        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

    protected void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取入参
        String queryName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        //角色
        int queryUserRole = 0;
        //每页最大容量可以前端传入，也可以写成配置项，这里暂时写死
        int pageSize = 5;
        int currentPageNo = 1;
        //参数处理
        if (temp != null && temp.length() > 0) {
            queryUserRole = Integer.parseInt(temp);
        }
        if (pageIndex != null && pageIndex.length() > 0) {
            currentPageNo = Integer.parseInt(pageIndex);
        }


        UserService userService = new UserServiceImpl();
        //获取用户总数(上一页，下一页)
        int totalCount = userService.getUserCount(queryName, queryUserRole);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = pageSupport.getTotalPageCount();
        //控制首页和尾页
        if (currentPageNo < 0) {
            currentPageNo = 0;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        //查询用户列表
        List<User> userList = userService.getUserList(queryName, queryUserRole, currentPageNo, pageSize);
        //获取角色列表
        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();


        req.setAttribute("userList", userList);
        req.setAttribute("roleList", roleList);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("queryUserName", queryName);
        req.setAttribute("queryUserRole", queryUserRole);

        req.getRequestDispatcher("userlist.jsp").forward(req, resp);
    }

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //参数处理
        //--gender
        String tempGender = req.getParameter("gender");
        int gender = StringUtils.isNullOrEmpty(tempGender) ? 1 : Integer.parseInt(tempGender);
        //--birthday
        String tempBirthday = req.getParameter("birthday");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthday = null;
        try {
            birthday = sdf.parse(tempBirthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //--userRole
        String tempUserRole = req.getParameter("userRole");
        int userRole = StringUtils.isNullOrEmpty(tempUserRole) ? 1 : Integer.parseInt(tempUserRole);
        //组装参数
        User user = new User();
        user.setUserCode(req.getParameter("userCode"));
        user.setUserName(req.getParameter("userName"));
        user.setUserPassword(req.getParameter("userPassword"));
        user.setGender(gender);
        user.setBirthday(birthday);
        user.setPhone(req.getParameter("phone"));
        user.setAddress(req.getParameter("address"));
        user.setUserRole(userRole);
        //service
        UserService userService = new UserServiceImpl();
        if (userService.addUser(user)) {
            //新增成功
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } else {
            //仍在当前页
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
